package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.iwhalecloud.citybrain.flow.platform.manager.application.common.enums.UserEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.User;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.FlowUserTenantAddVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.FlowUserTenantDeleteVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.tenant.FlowUserTenantVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowUserTenantRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowUserTenantInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowUserTenantInfoExample;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowUserTenantInfoDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author lilh
 * @date 2020/11/23 上午10:41
 */
@Repository
public class FlowUserTenantRepositoryImpl implements FlowUserTenantRepository {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FlowUserTenantInfoDAO flowUserTenantInfoDAO;

    @Override
    public boolean insertBatch(List<FlowUserTenantAddVo> addCols) {
        FlowUserTenantInfo entity;
        int count = 0;
        int ignoreCount = 0;
        List<FlowUserTenantInfo> userTenants = getUserTenant(addCols);
        Map<String, FlowUserTenantInfo> userCodeToItemMap = userTenants.stream().collect(Collectors.toMap(FlowUserTenantInfo::getUserCode, item -> item));
        for (FlowUserTenantAddVo vo : addCols) {
            //判断用户是否已经存在
            if (Objects.nonNull(userCodeToItemMap.get(vo.getUserCode()))) {
                ignoreCount++;
                continue;
            }
            entity = new FlowUserTenantInfo();
            BeanUtils.copyProperties(vo, entity);
            count += flowUserTenantInfoDAO.insertSelective(entity);
        }
        logger.info("待处理条数为：{}, 成功处理条数为:{}, 忽略条数为: {}", addCols.size(), count, ignoreCount);
        return addCols.size() == count;
    }

    private List<FlowUserTenantInfo> getUserTenant(List<FlowUserTenantAddVo> addCols) {
        Integer tenantId = addCols.get(0).getTenantId();
        FlowUserTenantInfoExample query = new FlowUserTenantInfoExample();
        query.createCriteria().andTenantIdEqualTo(tenantId)
                .andUserCodeIn(addCols.stream().map(FlowUserTenantAddVo::getUserCode).collect(Collectors.toList()));

        return flowUserTenantInfoDAO.selectByExample(query);
    }

    @Override
    public boolean delBatch(List<FlowUserTenantDeleteVo> delCols, Integer tenantId) {
        if (delCols.isEmpty()) {
            return true;
        }
        FlowUserTenantInfoExample query = new FlowUserTenantInfoExample();
        query.createCriteria().andIdIn(delCols.stream().map(FlowUserTenantDeleteVo::getId).collect(Collectors.toList()))
                .andTenantIdEqualTo(tenantId);
        flowUserTenantInfoDAO.deleteByExample(query);
        return true;
    }

    @Override
    public List<FlowUserTenantVo> listUsersByTenantId(Integer tenantId) {
        if (Objects.isNull(tenantId)) {
            return Collections.emptyList();
        }
        FlowUserTenantInfoExample query = new FlowUserTenantInfoExample();
        query.createCriteria().andTenantIdEqualTo(tenantId);
        List<FlowUserTenantInfo> flowUserTenantInfos = select(query);
        return flowUserTenantInfos.stream().map(this::convert).collect(Collectors.toList());
    }

    @Override
    public boolean hasAnotherTenant(Integer excludeTenantId, String userCode) {
        FlowUserTenantInfoExample query = new FlowUserTenantInfoExample();
        query.createCriteria().andUserCodeEqualTo(userCode).andTenantIdNotEqualTo(excludeTenantId);
        return flowUserTenantInfoDAO.selectByExample(query).size() > 0;
    }

    @Override
    public List<FlowUserTenantVo> listTenants(User current) {
        FlowUserTenantInfoExample query = new FlowUserTenantInfoExample();
        query.createCriteria().andUserCodeEqualTo(current.getUserCode());
        List<FlowUserTenantInfo> flowUserTenantInfos = select(query);
        return flowUserTenantInfos.stream().map(this::convert).collect(Collectors.toList());
    }

    private boolean isSuper(User current) {
        return Objects.equals(UserEnum.SUPER.type(), current.getUserType());
    }

    private List<FlowUserTenantInfo> select(FlowUserTenantInfoExample query) {
        return flowUserTenantInfoDAO.selectByExample(query);
    }

    private FlowUserTenantVo convert(FlowUserTenantInfo entity) {
        if (Objects.isNull(entity)) {
            return null;
        }
        FlowUserTenantVo result = new FlowUserTenantVo();
        BeanUtils.copyProperties(entity, result);
        return result;
    }
}
